package top.saplf.sileny.reader.main

import android.content.Intent
import android.os.Bundle
import android.support.design.widget.TabLayout.Tab
import android.view.View
import kotlinx.android.synthetic.main.fragment_reader_index.*
import top.saplf.sileny.R
import top.saplf.sileny.base.ui.SilenyFragment
import top.saplf.sileny.ext.TabSelectedAction
import top.saplf.sileny.ext.addOnTabSelectedListener
import top.saplf.sileny.main.home.MainActivity
import top.saplf.sileny.main.home.SimpleFragmentPagerAdapter
import top.saplf.sileny.reader.network.NetworkArticleIndexFragment
import top.saplf.sileny.reader.shelf.LocalBookIndexFragment

/**
 * @author Saplf
 */
class ReaderIndexFragment : SilenyFragment() {
    companion object {
        fun getInstance() = ReaderIndexFragment().apply {
            // todo
        }
    }

    private val tabSelectedAction: TabSelectedAction by lazy {
        {
            tab: Tab ->
            when (tab.position) {
                0 -> (activity as MainActivity).show()
                1 -> (activity as MainActivity).hide()
            }
        }
    }

    private val localPage by lazy { LocalBookIndexFragment.getInstance() }
    private val articlePage by lazy { NetworkArticleIndexFragment.getInstance() }

    private val localStr by lazy { getString(R.string.header_1_reader_local) }
    private val articleStr by lazy { getString(R.string.header_1_reader_article) }

    override fun onLayoutRes(): Int = R.layout.fragment_reader_index

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        viewPager.adapter = SimpleFragmentPagerAdapter(
                childFragmentManager,
                listOf(localPage, articlePage),
                listOf(localStr, articleStr)
        )
        tabLayout.setupWithViewPager(viewPager)
        tabLayout.addOnTabSelectedListener(tabSelectedAction, tabSelectedAction)
    }

    fun actionClick() {
        localPage.actionClick(activity)
    }

    fun currentIndex(): Int
            = viewPager.currentItem

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        localPage.onActivityResult(requestCode, resultCode, data)
    }
}